<template>
  <page ref="pages" @click="chatIndex=-1">
    <view class="head-info">
      <view class="title-tool">
        <view class="title">
          <text>聊天</text>
        </view>
      </view>
    </view>
    <!--    聊天列表-->
    <view class="chat-info">
      <view class="chat-list">
        <view class="list" v-for="(item,index) in chatList"
              @click="onChatItem(item,index)"
              @longpress="onLongChatItem(item,index,$event)"
              :key="index">
          <view class="operation-popup" :style="{top: chatInfo.top,left: chatInfo.left}" v-show="chatIndex===index">
            <view class="item" @click.stop="onDelChat(item,index)">
              <text>删除该聊天</text>
            </view>
          </view>
          <view class="pic">
            <fui-avatar :src="item.user_info.avatar_pic" width="100" height="100" shape="square"></fui-avatar>
            <fui-badge type="danger"
                       :value="item.msgNum"
                       :absolute="true" top="10rpx" right="30rpx"></fui-badge>
          </view>
          <view class="chat-item">
            <view class="name-date">
              <view class="name">
                <text>{{item.user_info.nickname}}</text>
              </view>
              <view class="date">
                <text>{{util.formatTime(item.msg_time,'{y}-{m}-{d} {h}:{i}')}}</text>
              </view>
            </view>
            <view class="content-tag">
              <view class="fail" v-if="item.isBlack === 1">
                <image src="/static/images/icon/fssb_icon.png"></image>
              </view>
              <view class="content" v-if="item.msgType === 'text' && !item.contentEmoji">
                <text class="one-omit">{{item.content}}</text>
              </view>
              <view class="content" v-else-if="item.msgType === 'text' && item.contentEmoji">
                <block v-for="value in item.contentEmoji">
                  <image :src="'/static/images/emoji/'+value+'.png'" v-if="emojiItems.includes(value)"></image>
                  <text class="one-omit" v-else>{{value}}</text>
                </block>
              </view>
              <view class="content" v-else-if="item.msgType === 'image'">
                <text class="one-omit">[图片]</text>
              </view>
              <view class="content" v-else-if="item.msgType === 'voice'">
                <text class="one-omit">[语音]</text>
              </view>
              <view class="content" v-else-if="item.msgType === 'redPacket'">
                <text class="one-omit">[红包]</text>
              </view>
              <view class="tag">
              </view>
            </view>
          </view>
        </view>
      </view>
      <empty icon="/static/images/empty/empty_zwxi.png" hint="暂无聊天，快去找朋友聊天吧" v-show="chatList.length === 0"></empty>
    </view>
    <tab-bar selectStr="聊天"></tab-bar>
  </page>
</template>

<script setup>
import {onReady, onLoad, onShow} from "@dcloudio/uni-app";
import TabBar from "../../components/TabBar/TabBar";
import {chatHomeList, deleteChat} from "../../api/api";
import {getCurrentInstance, ref, watch} from "vue";
import util from "../../common/util";
import emoji from "../../common/emoji";
import {useStore} from "vuex";
import Empty from "../../components/empty/empty.vue";


const {proxy} = getCurrentInstance();
const store = useStore();
const pages = ref(null);
const chatList = ref([]);
// 表情列表
const emojiItems = emoji;
// 聊天操作数据
const chatInfo = ref({
  top: 0,
  left: 0,
});
const chatIndex = ref(-1);

onReady(() => {
  uni.hideTabBar();
})
onLoad(() => {

})
onShow(() =>{
  getData();
})
function getData() {
  chatHomeList({
  }).then(res =>{
    for (let i = 0; i < res.data.length; i++) {
      res.data[i].msgNum = 0;
      res.data[i].contentEmoji = util.emojiMatch(res.data[i].content);
    }
    console.log(res);
    chatList.value = res.data;
    queryChatList();
  })
}

/**
 * 聊天点击
 * @param item
 */
function onChatItem(item,index){
  if(chatIndex.value >= 0){
    return;
  }
  proxy.$global.toUserInfo = item.user_info;
  store.commit('setCountMsg',store.state.chat.countMsg - chatList.value[index].msgNum);
  chatList.value[index].msgNum = 0;
  // 循环查找对应列表删除未读消息
  for (let i = 0; i < store.state.chat.chatList.length;i++) {
    if(store.state.chat.chatList[i].to_user_id === item.to_user_id){
      store.state.chat.chatList.splice(i,1);
      i = i - 1;
    }
  }
  uni.navigateTo({
    url: `/pages/ChatPage/ChatPage?to_user_id=${item.to_user_id}`,
  })
}

/**
 * 聊天长按
 * @param item
 * @param index
 * @param e
 */
function onLongChatItem(item,index,e){
  item.left = e.target.offsetLeft + 'px';
  item.top = e.target.offsetTop + 'px';
  chatInfo.value = item;
  chatIndex.value = index;
}

/**
 * 删除聊天点击
 * @param item
 * @param index
 */
function onDelChat(item,index){
  uni.showModal({
    title: '提示',
    content: '确定要删除此聊天吗？',
    success: (res) =>{
      if (!res.confirm) {
        return;
      }
      deleteChat({
        chat_list_id: item.chat_list_id,
      }).then(res =>{
        chatList.value.splice(index,1);
        chatIndex.value = -1;
      })
    }
  })
}
/**
 * 查找聊天用户
 * @param data
 */
function queryChatUser(data = {}){
  let index = 0;
  let isFind = false;
  console.log(1111111);
  for (let i = 0; i < chatList.value.length; i++) {
    if(data.to_user_id === chatList.value[i].to_user_id){
      chatList.value[i].msgNum += 1;
      chatList.value[i].msg_time = data.create_time;
      chatList.value[i].content = data.content;
      chatList.value[i].msgType = data.msgType;
      chatList.value[i].contentEmoji = util.emojiMatch(data.content);
      index = i;
      isFind = true;
    }
  }
  console.log(isFind);
  // 没有存在会话列表 获取数据
  if(!isFind){
    getData();
    return;
  }
  swapArray(chatList.value, 0, index)
}

/**
 * 交换数组里位置
 * @param arr
 * @param index1
 * @param index2
 * @returns {*}
 */
function swapArray(arr, index1, index2) {
  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
}
/**
 * 查找聊天列表
 */
function queryChatList(){
  let chatArr = store.state.chat.chatList;
  for (let i = 0; i < chatArr.length; i++) {
    for (let j = 0; j < chatList.value.length; j++) {
      if(chatArr[i].to_user_id === chatList.value[j].to_user_id){
        chatList.value[j].msgNum += 1;
        chatList.value[j].msg_time = chatArr[i].create_time;
        chatList.value[j].content = chatArr[i].content;
        chatList.value[j].msgType = chatArr[i].msgType;
        chatList.value[j].contentEmoji = util.emojiMatch(chatArr[i].content);
      }
    }
  }
}
watch(
    () => store.state.chat.chatData,
    (newVal) =>{
      if(newVal._id){
        queryChatUser(newVal);
      }
    }
)
</script>

<style lang="scss">
@import "home.scss";
</style>
